package test;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SearchFriendServlet extends HttpServlet implements Servlet {
	public SearchFriendServlet() {
		// 

	}

	@Override
	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		doPost(arg0, arg1);
	
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html");
	

		//
		// response.sendRedirect ( "index.jsp" );
		String SearchWord = request.getParameter("keyword");
	
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		//String url = "jdbc:postgresql://localhost:5432/postgres";
		String url = "jdbc:postgresql://localhost:5432/lmb";
		List<User> list = new ArrayList<User>();
		java.sql.Connection connection = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			connection = DriverManager.getConnection(url, "gxc", "gxc");
			stmt = connection.createStatement();
			//

			String sql = "select * from userinfo where username LIKE '%" + SearchWord +"%'"
//					+ " OR uid  =" + SearchWord 
					+ " OR uphone LIKE '%" + SearchWord + "%'";
//					+ " OR ubirth = '" + SearchWord + "'";
			
			rs = stmt.executeQuery(sql);

		} catch (SQLException e) {
			// 

			e.printStackTrace();
		}
		try {
			if (rs != null)
			{
				while (rs.next())
	
				{
					User tmpUser = new User();
					
					tmpUser.setUsername(rs.getString("username"));
					tmpUser.setUid(rs.getInt("uid"));
					tmpUser.setUphone(rs.getString("uphone"));
					tmpUser.setUbirth(rs.getDate("ubirth"));
					tmpUser.setSex(rs.getString("usex"));
	
					list.add(tmpUser);
				}
				
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/DisplayUserREsult.jsp");
				request.getSession().setAttribute("userList", list);
				rd.forward(request,response);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		}
		try {
			if (null != rs) {
				rs.close();
			}
			if (null != stmt) {
				stmt.close();
			}
			if (null != connection) {
				connection.close();
			}
		} catch (SQLException e) {
			

			e.printStackTrace();
		}
	}

	private static final long serialVersionUID = 1L;
}
